/*
 * http_c.h
 *
 *  Created on: Oct 24, 2013
 *      Author: killerg
 */

#ifndef HTTP_C_H_
#define HTTP_C_H_

#include <event2/http.h>
#include <event2/dns.h>
#include <event2/util.h>
#include <event2/event.h>
#include <functional>
#include <list>
#include <memory>
#include "patterns.h"

struct evhttp_connection;

class http_client {
    public:
        typedef std::function<void(int, const std::string&)> client_cb_t;
        struct request_t {
            std::string host;
            std::string uri;
            int port;

            std::string body;
            client_cb_t cb;
            http_client* cli;
        };

        struct host_t {
            std::string head_part;
            evhttp_connection* conn;
            bool querying;
            std::list<request_t*> req_list;

            bool add_request(request_t* request);
            bool try_do_request();
        };

        host_t* get_host(const char* host, int port);
        void dealloc_request(request_t* &request);
        request_t* alloc_request(
                const char* host,
                int port,
                const char* uri,
                const char* body,
                http_client* cli,
                client_cb_t cb);

        ptr_map<std::string, host_t*> head_host_map;
        ptr_map<evhttp_connection*, host_t*> conn_host_map;

        bool do_query(
                const char* url,
                const char* body,
                client_cb_t cb = NULL);

        bool init();
        void destroy();
        void update();

        int pending_num() { return _pending_num; }

        int _pending_num;
    private:
        evdns_base* dns_base;
        event_base* base;

};


#endif /* HTTP_C_H_ */
